package com.xwtec.proxy.v7;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * @Author: zt
 * @Date: 2021/3/4 20:41
 */
public class Main {

    public static void main(String[] args) {
        Enhancer enhancer =new Enhancer();
        enhancer.setSuperclass(Tank.class);
        enhancer.setCallback(new LogMethodInterceptor());
         Tank tank = (Tank)enhancer.create();
         //实际调用子类的方法
         tank.move();
    }



}

class Tank{

    public int move() {
        System.out.println("Tank Move claclacla.....");
        try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }
}


//代理类，实际上是Tank类的子类
class LogMethodInterceptor implements MethodInterceptor{

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println(o.getClass().getSuperclass().getName());
        System.out.println("before");
        Object result = null;
        result=methodProxy.invokeSuper(o, objects);
        System.out.println("after");
        return result;
    }
}

